package com.stn.zjx.givingtreasure.activity.dynamic;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.android.flexbox.FlexboxLayout;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.irozon.sneaker.Sneaker;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DateUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;
import com.lzy.okserver.OkUpload;
import com.lzy.okserver.task.XExecutor;
import com.lzy.okserver.upload.UploadListener;
import com.lzy.okserver.upload.UploadTask;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.activity.common.DropImgsShowActivity;
import com.stn.zjx.givingtreasure.activity.location.UserLocationActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.FileInputstreamUploadDomain;
import com.stn.zjx.givingtreasure.domain.FileUploadDomain;
import com.stn.zjx.givingtreasure.domain.FileUploadMutiDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.LocationEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.SubmitRefreshEvent;
import com.stn.zjx.givingtreasure.glide.GlideCacheUtil;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.FileApi;
import com.stn.zjx.givingtreasure.net.impl.FileNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicNetImpl;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.Base64FileUtils;
import com.stn.zjx.givingtreasure.utils.OpenLocalMapUtil;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxImageTool;
import com.vondear.rxtools.RxPhotoTool;
import com.white.progressview.HorizontalProgressView;
import com.yalantis.ucrop.UCrop;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class ReleaseDynamicActivity extends BaseActivity implements AMapLocationListener, XExecutor.OnAllTaskEndListener {
    private static final int PRC_PHOTO_PICKER = 1001;
    private static final int SELECT_PHOTO = 1002;
    private static final int SELECT_VIDEO = 1003;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.gray_camera)
    ImageView grayCamera;
    @BindView(R.id.gray_location)
    ImageView grayLocation;
    @BindView(R.id.add_location_tv)
    TextView addLocationTv;
    @BindView(R.id.add_location)
    RelativeLayout addLocation;
    public String province = "";
    public String city = "";
    public String area = "";
    public String address = "";
    public String longitude = "";
    public String latitude = "";
    @BindView(R.id.flex)
    FlexboxLayout flex;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.up_imgs)
    RelativeLayout upImgs;
    private Uri resultUri;
  //  BottomDialog uploadDialog;
    public List<String> imgs = new ArrayList<>();
    AmapLocationService amapLocationService = null;
     public String dynamicVideoPath="";
    public long dynamicVideoTime=0L;
    public String dynamicImg="";
    private BottomDialog uploadSelectDialog;

   public int openType=0;
   private OkUpload okUpload;
    public String tag="update_ok_upload_imgs";
    Integer dynamicVideoWidth=0;
    Integer dynamicVideoHeight=0;
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        okUpload=OkUpload.getInstance();
        okUpload.getThreadPool().setCorePoolSize(1);
        okUpload.addOnAllTaskEndListener(this);
        actionTitle.setText(getString(R.string.release_dynamic));
        releaseBt.setVisibility(View.VISIBLE);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_dynamic);
        ButterKnife.bind(this);
        initComponent();
        initUploadDialog();
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        if (EasyPermissions.hasPermissions(this, perms)) {
            startLocation();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }

    }

    public void startLocation() {
        showLoading();
        amapLocationService = new AmapLocationService(this);
        amapLocationService.registerListener(this);
        amapLocationService.start();

    }

    public void initUploadDialog() {
//        uploadDialog = BottomDialog.create(getSupportFragmentManager())
//                .setLayoutRes(R.layout.dialog_select_images)
//                .setCancelOutside(false)
//                .setDimAmount(0.4f)
//                .setViewListener(new BottomDialog.ViewListener() {
//                    @Override
//                    public void bindView(View v) {
//                        v.findViewById(R.id.cancel)
//                                .setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//                                        uploadDialog.dismiss();
//
//                                    }
//                                });
//                        v.findViewById(R.id.location_upload)
//                                .setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//                                        uploadDialog.dismiss();
//                                        choicePhoto(1);
//                                    }
//                                });
//                        v.findViewById(R.id.camera_upload)
//                                .setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//                                        uploadDialog.dismiss();
//                                        choicePhoto(0);
//                                    }
//                                });
//                    }
//                });

        uploadSelectDialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_select_video_images)
                .setCancelOutside(false)
                .setDimAmount(0.4f)
                .setTag("uploadSelectDialog")
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.cancel)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadSelectDialog.dismiss();

                                    }
                                });
                        v.findViewById(R.id.img_upload)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadSelectDialog.dismiss();

                                        if(!TextUtils.isEmpty(dynamicVideoPath)){
                                            showToast(getString(R.string.already_select_tip1));
                                            return;
                                        }

                                        openType=0;
                                        selectPhotoVideos(openType);
                                    }
                                });
                        v.findViewById(R.id.video_upload)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadSelectDialog.dismiss();
                                        if(imgs.size()!=0){
                                            showToast(getString(R.string.already_select_tip));
                                            return;
                                        }
                                        openType=1;
                                        selectPhotoVideos(openType);
                                    }
                                });

                    }
                });

    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void choicePhoto(int openType) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            switch (openType) {
                case 0:
                    RxPhotoTool.openCameraImage(this);
                    break;
                case 1:
                    RxPhotoTool.openLocalImage(this);
                    break;
            }

        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void selectPhotoVideos(int openType) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            switch (openType) {
                case 0:
                    openImages();
              //      RxPhotoTool.openCameraImage(this);
                    break;
                case 1:
                //    RxPhotoTool.openLocalImage(this);
                    openVideo();
                    break;
            }

        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case SELECT_PHOTO:
                // 图片选择结果回调
            List<LocalMedia>    selectList = PictureSelector.obtainMultipleResult(data);

                if(selectList!=null&&selectList.size()!=0){
                     if(selectList.size()+imgs.size()>9){
                         showToast(getString(R.string.img_limit));
                         return;
                     }
                      for(int i=0;i<selectList.size();i++){
                           LocalMedia media=selectList.get(i);
                         String myPath;
                            if(media.isCompressed()){
                                myPath=media.getCompressPath();
                            }else{
                                myPath=media.getPath();
                            }
                          View img_view = View.inflate(getApplicationContext(), R.layout.item_show_imgs, null);
                          View exit = img_view.findViewById(R.id.exit);
                          ImageView iv = img_view.findViewById(R.id.iv);
                          exit.setOnClickListener(new View.OnClickListener() {
                              @Override
                              public void onClick(View view) {
                                  imgs.remove(myPath);
                                  flex.removeView(img_view);
                              }
                          });
                          Glide.with(ReleaseDynamicActivity.this)
                                  .load(media.getCompressPath())
                                  .into(new SimpleTarget<Drawable>() {
                                      @Override
                                      public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                          iv.setImageDrawable(resource);
                                      }
                                  });
                          iv.setOnClickListener(new View.OnClickListener() {
                              @Override
                              public void onClick(View view) {
                                  int pos=0;
                                    for(int  i=0;i<imgs.size();i++){
                                        if(myPath.equals(imgs.get(i))){
                                            pos=i;
                                        }
                                    }
                                  Intent intent=new Intent(ReleaseDynamicActivity.this, DropImgsShowActivity.class);
                                  int[] location=new int[2];
                                  iv.getLocationOnScreen(location);
                                  intent.putExtra("left", location[0]);
                                  intent.putExtra("top", location[1]);
                                  intent.putExtra("height", iv.getHeight());
                                  intent.putExtra("width",iv.getWidth());
                                  intent.putExtra("position",pos);
                                  intent.putStringArrayListExtra("imgs", (ArrayList<String>) imgs);
                                  overridePendingTransition(0, 0);
                                  startActivity(intent);
                              }
                          });
                          imgs.add(myPath);
                          flex.addView(img_view, 0);
                     }

                }


                // 例如 LocalMedia 里面返回两种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true

                break;
            case SELECT_VIDEO:
                List<LocalMedia>    video_selectList = PictureSelector.obtainMultipleResult(data);
                   if(video_selectList!=null&&video_selectList.size()!=0){
                       if(!TextUtils.isEmpty(dynamicVideoPath)){
                           showToast(getString(R.string.video_limit));
                           return;
                       }
                       for(int i=0;i<video_selectList.size();i++){
                           LocalMedia media=video_selectList.get(i);
                           View video_view = View.inflate(getApplicationContext(), R.layout.item_show_videos, null);
                           View exit = video_view.findViewById(R.id.exit);
                           ImageView iv = video_view.findViewById(R.id.iv);
                           TextView tv_duration = video_view.findViewById(R.id.tv_duration);
                           tv_duration.setText(DateUtils.timeParse(media.getDuration()));
                           exit.setOnClickListener(new View.OnClickListener() {
                               @Override
                               public void onClick(View view) {
                                    dynamicVideoPath="";
                                    dynamicVideoTime=0L;
                                     dynamicImg="";
                                   dynamicVideoWidth=0;
                                   dynamicVideoHeight=0;
                                    flex.removeView(video_view);
                               }
                           });
                           Glide.with(ReleaseDynamicActivity.this)
                                   .asBitmap()
                                   .load(media.getPath())
                                   .into(new SimpleTarget<Bitmap>() {
                                       @Override
                                       public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                           iv.setImageBitmap(resource);
                                           dynamicVideoWidth=resource.getWidth();
                                           dynamicVideoHeight=resource.getHeight();
                                           File file=new File(getCacheDir().getPath()+UUID.randomUUID().toString()+".png");
                                           boolean isSave=  RxImageTool.save(resource,file.getPath(), Bitmap.CompressFormat.PNG);
                                           if(isSave){
                                               dynamicImg=file.getPath();
                                           }
                                       }
                                   });
                           iv.setOnClickListener(new View.OnClickListener() {
                               @Override
                               public void onClick(View view) {
                                   // 预览视频
                                   PictureSelector.create(ReleaseDynamicActivity.this).externalPictureVideo(media.getPath());
                               }
                           });
                           dynamicVideoPath=media.getPath();
                           dynamicVideoTime=media.getDuration();

                           flex.addView(video_view, 0);
//                           System.out.println("**********************getCompressPath:"+media.getCompressPath());
//                           System.out.println("**********************getPath:"+media.getPath());
//                           System.out.println("**********************getMimeType:"+media.getMimeType());
//                           System.out.println("**********************getWidth:"+media.getWidth());
//                           System.out.println("**********************getHeight:"+media.getHeight());
//                           System.out.println("**********************getDuration:"+media.getDuration());
//                           System.out.println("**********************getNum:"+media.getNum());
                       }

                   }
                break;
        }


//            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
//                try {
//                    Glide
//                            .with(ReleaseDynamicActivity.this)
//                            .asBitmap()
//                            .load(data.getData())
//                            .into(new SimpleTarget<Bitmap>() {
//                                @Override
//                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                                    Bitmap newbitmap = ToolsUtils.comp(resource);
//                                    File new_file = new File(getCacheDir().getPath() + "/" + UUID.randomUUID().toString() + ".png");
//                                    boolean is = RxImageTool.save(newbitmap, new_file, Bitmap.CompressFormat.PNG);
//                                    if (is) {
//                                        uploadAvatar(new_file);
//                                    } else {
//                                        showToast(getString(R.string.no_cache_data));
//                                    }
//                                }
//                            });
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    showToast(e.getMessage());
//                }
//
//                //    initUCrop(data.getData(), false);
//                break;
//            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
//                try {
//                    Glide
//                            .with(ReleaseDynamicActivity.this)
//                            .asBitmap()
//                            .load(RxPhotoTool.imageUriFromCamera)
//                            .into(new SimpleTarget<Bitmap>() {
//                                @Override
//                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                                    Bitmap newbitmap = ToolsUtils.comp(resource);
//                                    File new_file = new File(getCacheDir().getPath() + "/" + UUID.randomUUID().toString() + ".png");
//                                    boolean is = RxImageTool.save(newbitmap, new_file, Bitmap.CompressFormat.PNG);
//                                    if (is) {
//                                        uploadAvatar(new_file);
//                                    } else {
//                                        showToast(getString(R.string.no_cache_data));
//                                    }
//                                }
//                            });
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    showToast(e.getMessage());
//                }
//                //  initUCrop(RxPhotoTool.imageUriFromCamera, false);
//                break;
//            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
//                resultUri = UCrop.getOutput(data);
//                File file = new File(Objects.requireNonNull(RxPhotoTool.getImageAbsolutePath(this, resultUri)));
//
//
//                break;
//            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
//                final Throwable cropError = UCrop.getError(data);
//                assert cropError != null;
//                showToast(cropError.getMessage());
//                break;
      //  }
    }


//    public void uploadAvatar(File file) {
//
//        String base = Base64FileUtils.encryptToBase64(file.getAbsolutePath());
//        JSONObject data = new JSONObject();
//        try {
//            data.put("upfileBase64Content", base);
//            data.put("upfileName", "" + new Date().getTime());
//            data.put("upfileSuffix", "png");
//            data.put("upfiletype", "0");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        FileNetImpl
//                .upload_base64_file(data.toString(), "upload_base64_file", new StringCallback() {
//                    @Override
//                    public void onStart(Request<String, ? extends Request> request) {
//                        super.onStart(request);
//                        showLoading();
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        super.onFinish();
//                        dissmissLoading();
//                    }
//
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        if (response.isSuccessful() && !isFinishing()) {
//                            Gson gson = new Gson();
//                            FileUploadDomain domain = gson.fromJson(response.body(), FileUploadDomain.class);
//                            switch (domain.getStatus()) {
//                                case BaseApi.REQUEST_SUCCESS_CODE:
//                                    imgs.add(domain.getData().getPath());
//                                    View img_view = View.inflate(getApplicationContext(), R.layout.item_show_imgs, null);
//                                    View exit = img_view.findViewById(R.id.exit);
//                                    ImageView iv = img_view.findViewById(R.id.iv);
//                                    exit.setOnClickListener(new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View view) {
//                                            imgs.remove(domain.getData().getPath());
//                                            flex.removeView(img_view);
//                                        }
//                                    });
//                                    Glide.with(ReleaseDynamicActivity.this)
//                                            .load(file)
//                                            .into(new SimpleTarget<Drawable>() {
//                                                @Override
//                                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
//                                                    iv.setImageDrawable(resource);
//                                                }
//                                            });
//                                    img_view.setOnClickListener(new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View view) {
//                                            PictureSelector.create(ReleaseDynamicActivity.this).externalPicturePreview(position, "/", null);
//                                        }
//                                    });
//                                    flex.addView(img_view, 0);
//                                    break;
//                                default:
//                                    showToast(domain.getMessage());
//                                    break;
//                            }
//
//                        }
//                    }
//                });
//
//    }


    public void uploadImges() {
           if(imgs.size()==0){
              showToast(getString(R.string.upload_img_is_not_null));
               return;
           }
        showLoading();
        JSONObject data = new JSONObject();
        try {
            JSONArray ja=new JSONArray();
          for(int i=0;i<imgs.size();i++){
                   ja.put(Base64FileUtils.encryptToBase64(imgs.get(i)));
          }
            data.put("upfileBase64Content", ja);
            data.put("upfileName", "" + new Date().getTime());
            data.put("upfileSuffix", "png");
            data.put("upfiletype", "0");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        FileNetImpl
                .upload_base64_file_mutiupload(data.toString(), "upload_base64_file_mutiupload", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            Gson gson = new Gson();
                            FileUploadMutiDomain domain = gson.fromJson(response.body(), FileUploadMutiDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                          String img="";
                 if(domain.getData().getPath().size()!=0){
                    for(int i=0;i<domain.getData().getPath().size();i++){
                         String s=domain.getData().getPath().get(i);
                        if(i==0){
                            img=img+s;
                        }else{
                            img=img+"*"+s;
                        }
                    }
                 }
                addDynamic(contentEdit.getText().toString().trim(),
                        province,
                        city,
                        area,
                        address,
                        img,
                        dynamicVideoPath,
                        0L,
                        0L,
                        0,
                        0,
                        Double.parseDouble(longitude),
                        Double.parseDouble(latitude)
                        );

                                    break;
                                default:
                                    showToast(domain.getMessage());
                                    break;
                            }
                        }
                    }
                });

    }

    public void uploadVideos() {
        if(TextUtils.isEmpty(dynamicVideoPath)){
            showToast(getString(R.string.upload_video_is_not_null));
            return;
        }
   //     showLoading();
        Dialog pb=new Dialog(this);
        pb.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pb.setCanceledOnTouchOutside(false);
        pb.setContentView(R.layout.dialog_upload_progress_loading);
        PostRequest<String> postRequest=OkGo.<String>post(FileApi.pc_uploadmutifile_bigupload)
                .params("file",new File(dynamicVideoPath))
                .converter(new StringConvert());
          UploadTask<String> task=OkUpload.request(tag,postRequest)
                     .priority(100)
                     .save()
                     .register(new UploadListening<>(tag,pb));
        task.start();
//        JSONObject data = new JSONObject();
//        try {
//            data.put("upfileBase64Content", Base64FileUtils.encryptToBase64(dynamicVideoPath));
//            data.put("upfileName", "" + new Date().getTime());
//            data.put("upfileSuffix", ""+dynamicVideoPath.substring(dynamicVideoPath.lastIndexOf(".")+1,dynamicVideoPath.length()));
//            data.put("upfiletype", "2");
//        } catch (JSONException e) {
//            e.printStackTrace();
//            dissmissLoading();
//        }
//        dissmissLoading();
//        System.out.println("*************************dynamicVideoPath"+dynamicVideoPath);
//        System.out.println("*************************dynamicVideoPath"+dynamicVideoPath.substring(dynamicVideoPath.lastIndexOf(".")+1,dynamicVideoPath.length()));
//        FileNetImpl
//                .upload_base64_file(data.toString(), "upload_base64_file", new StringCallback() {
//
//                    @Override
//                    public void uploadProgress(Progress progress) {
//                        super.uploadProgress(progress);
//                        hp_pb.setMax(100);
//                        hp_pb.setProgress((int) ((progress.currentSize/progress.totalSize)*100));
//                        num.setText(progress.currentSize+"/"+progress.totalSize);
//                    }
//                    @Override
//                    public void onStart(Request<String, ? extends Request> request) {
//                        super.onStart(request);
//                        pb.show();
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        super.onFinish();
//                        pb.dismiss();
//                    }
//
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        if (response.isSuccessful() && !isFinishing()) {
//                            Gson gson = new Gson();
//                            FileUploadDomain domain = gson.fromJson(response.body(), FileUploadDomain.class);
//                            switch (domain.getStatus()) {
//                                case BaseApi.REQUEST_SUCCESS_CODE:
//                                    String img="";
//
//                                    addDynamic(contentEdit.getText().toString().trim(),
//                                            province,
//                                            city,
//                                            area,
//                                            address.substring((province+city+area).length(),address.length()),
//                                            img,
//                                            domain.getData().getPath(),
//                                            dynamicVideoTime,
//                                            domain.getData().getSize(),
//                                            Double.parseDouble(longitude),
//                                            Double.parseDouble(latitude)
//                                    );
//                                    break;
//                                default:
//                                    showToast(domain.getMessage());
//                                    break;
//                            }
//                        }
//                    }
//                });

    }


    @OnClick({R.id.back_bt, R.id.action_title, R.id.add_location, R.id.up_imgs, R.id.release_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.up_imgs:
//                if (imgs.size() == 9) {
//                    Toast.makeText(getApplicationContext(), getString(R.string.max_imgs_limit_9), Toast.LENGTH_SHORT).show();
//                    return;
//                }

                uploadSelectDialog.show();

                //uploadDialog.show();
                break;
            case R.id.back_bt:
                finish();
                break;
            case R.id.add_location:
                RxActivityTool.skipActivity(getApplicationContext(), UserLocationActivity.class);
                break;
            case R.id.release_bt:
                User onlineUser = UserService
                        .getInstance(this)
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(this, UserLoginActivity.class);
                    return;
                }
                if (TextUtils.isEmpty(contentEdit.getText().toString().trim())) {
                     showToast(getString(R.string.content_is_not_null));
                    return;
                }
                if(TextUtils.isEmpty(address)){
                    showToast(getString(R.string.location_address_isnot_null));
                    return;
                }
                if(TextUtils.isEmpty(dynamicVideoPath)&&imgs.size()==0){
                    showToast(getString(R.string.upload_imgs_or_video));
                    return;
                }
                 if(imgs.size()!=0){
                     uploadImges();
                 }else {
                     uploadVideos();
                 }

                break;

        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocationEvent(LocationEvent event) {
        if (event.flag != 1) {
            return;
        }
        province = event.province;
        city = event.city;
        area = event.area;
        address = event.address;
        longitude = event.longitude;
        latitude = event.latitude;
        addLocationTv.setTextColor(getResources().getColor(R.color.default_black));
        addLocationTv.setText(address);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
//         showToast(aMapLocation.getAddress());
        if (aMapLocation.getErrorCode() == 0) {
            province = aMapLocation.getProvince();
            city = aMapLocation.getCity();
            area = aMapLocation.getDistrict();
            if(aMapLocation.getAddress().length()<(province.length()+city.length()+area.length())){
                address = aMapLocation.getAddress();
            }else{
                address = aMapLocation.getAddress().substring(province.length()+city.length()+area.length(),aMapLocation.getAddress().length());
            }
            longitude = aMapLocation.getLongitude() + "";
            latitude = aMapLocation.getLatitude() + "";
            addLocationTv.setTextColor(getResources().getColor(R.color.default_black));
            addLocationTv.setText(String.valueOf(address));
        } else {
            showToast(aMapLocation.getErrorInfo());
        }
        dissmissLoading();
    }

    public void addDynamic(String dynamicContent,
                           String dynamicProvince,
                           String dynamicCity,
                           String dynamicArea,
                           String dynamicAddress,
                           String dynamicImgs,
                           String dynamicVideoPath,
                           Long dynamicVideoSize,
                           Long dynamicVideoTime,
                           Integer dynamicVideoWidth,
                           Integer dynamicVideoHeight,
                           double locationLongitude,
                           double locationLatitude){
        User onlineUser= UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
        if(onlineUser==null){
             return;
         }
        UserDynamicNetImpl
                .ad_dynamic(onlineUser.getToken(),
                        dynamicContent,
                        dynamicProvince ,
                        dynamicCity,
                        dynamicArea,
                        dynamicAddress,
                        dynamicImgs,
                        dynamicVideoPath,
                        dynamicVideoSize,
                        dynamicVideoTime,
                        dynamicVideoWidth,
                        dynamicVideoHeight,
                        locationLongitude,
                        locationLatitude, "ad_dynamic", new StringCallback() {
                            @Override
                            public void onFinish() {
                                super.onFinish();
                             dissmissLoading();
                            }

                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                              showLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                                 switch (domain.getStatus()){
                                     case BaseApi.REQUEST_SUCCESS_CODE:
                                     // showToast(domain.getMessage());
                                         SubmitRefreshEvent event=new SubmitRefreshEvent();
                                         event.flag=SubmitRefreshEvent.SubmitDynamicRefresh;
                                         EventBus.getDefault().post(event);
                                        finish();
                                         break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;

                                 }
                            }
                        });


    }





    public void openImages(){
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(ReleaseDynamicActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                .theme(R.style.picture_white)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(9)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(false)// 是否可预览视频 true or false
                .enablePreviewAudio(false) // 是否可播放音频  true or false
                .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.THIRD_GEAR、Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                .isCamera(true)// 是否显示拍照按钮 ture or false
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath(getCacheDir().getPath())// 自定义拍照保存路径,可不填
                .compress(true)// 是否压缩 true or false
                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                .glideOverride(300,300)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度 int
                .isGif(true)// 是否显示gif图片 true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                .selectionMedia(null)// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .compressMaxKB(500)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                .compressWH(1,1) // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效 int
                .videoQuality(1)// 视频录制质量 0 or 1 int
                .videoSecond(60*60)//显示多少秒以内的视频or音频也可适用 int
                .recordVideoSecond(60)//录制视频秒数 默认60s int
                .forResult(SELECT_PHOTO);//结果回调onActivityResult code
    }

    public void openVideo(){
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(ReleaseDynamicActivity.this)
                .openGallery(PictureMimeType.ofVideo())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                .theme(R.style.picture_white)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(3)// 每行显示个数 int
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(true)// 是否可预览视频 true or false
                .enablePreviewAudio(true) // 是否可播放音频  true or false
                .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.THIRD_GEAR、Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                .isCamera(true)// 是否显示拍照按钮 ture or false
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath(getCacheDir().getPath())// 自定义拍照保存路径,可不填
                .compress(true)// 是否压缩 true or false
                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                .glideOverride(300,300)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度 int
                .isGif(true)// 是否显示gif图片 true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                .selectionMedia(null)// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .compressMaxKB(500)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                .compressWH(1,1) // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效 int
                .videoQuality(1)// 视频录制质量 0 or 1 int
                .videoSecond(60*60)//显示多少秒以内的视频or音频也可适用 int
                .recordVideoSecond(60*60)//录制视频秒数 默认60s int
                .forResult(SELECT_VIDEO);//结果回调onActivityResult code


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        okUpload.removeOnAllTaskEndListener(this);
        okUpload.removeTask(tag);
    }

    @Override
    public void onAllTaskEnd() {

    }

    public class UploadListening<String> extends UploadListener<String>{
         public Dialog dialog;
         public TextView num;
         public HorizontalProgressView hp_pb;
        public UploadListening(Object tag,Dialog dialog) {
            super(tag);
            this.dialog=dialog;
            num=dialog.findViewById(R.id.num);
             hp_pb=dialog.findViewById(R.id.pb);
        }

        @Override
        public void onStart(Progress progress) {
            num.setText("0/"+ToolsUtils.getFormatSize(progress.totalSize));
            hp_pb.setProgress(0);
            hp_pb.setMax(100);
            dialog.show();
        }

        @Override
        public void onProgress(Progress progress) {
            num.setText(ToolsUtils.getFormatSize(progress.currentSize)+"/"+ToolsUtils.getFormatSize(progress.totalSize));
            hp_pb.setProgress((int) (progress.fraction * 100));
        }

        @Override
        public void onError(Progress progress) {
            dialog.dismiss();
        }

        @Override
        public void onFinish(String t, Progress progress) {
            dialog.dismiss();
                Gson gson = new Gson();
                FileInputstreamUploadDomain domain = gson.fromJson((java.lang.String) t, FileInputstreamUploadDomain.class);
                switch (domain.getStatus()) {
                    case BaseApi.REQUEST_SUCCESS_CODE:
                        domain.getData().get(0);
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                           FileInputstreamUploadDomain.DataBean   dataBean= domain.getData().get(0);
                            JSONObject data=new JSONObject();
                            try {
                                JSONArray ja=new JSONArray();
                                ja.put(Base64FileUtils.encryptToBase64(dynamicImg));
                                data.put("upfileBase64Content",ja);
                                data.put("upfileName", "" + new Date().getTime());
                                data.put("upfileSuffix", "png");
                                data.put("upfiletype", "0");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            FileNetImpl
                                    .upload_base64_file_mutiupload(data.toString(), "upload_base64_file_mutiupload", new StringCallback() {
                                        @Override
                                        public void onStart(Request<java.lang.String, ? extends Request> request) {
                                            super.onStart(request);
                                            showLoading();
                                        }
                                        @Override
                                        public void onFinish() {
                                            super.onFinish();
                                            dissmissLoading();
                                        }

                                        @Override
                                        public void onSuccess(Response<java.lang.String> response) {
                                            if (response.isSuccessful() && !isFinishing()) {
                                                Gson gson = new Gson();
                                                FileUploadMutiDomain domain = gson.fromJson(response.body(), FileUploadMutiDomain.class);
                                                switch (domain.getStatus()) {
                                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                                        java.lang.String img="";
                                                        if(domain.getData().getPath().size()!=0){
                                                            img=domain.getData().getPath().get(0);
                                                            addDynamic(contentEdit.getText().toString().trim(),
                                                                    province,
                                                                    city,
                                                                    area,
                                                                    address,
                                                                    img,
                                                                    dataBean.getPath(),
                                                                    dataBean.getSize(),
                                                                    dynamicVideoTime,
                                                                    dynamicVideoWidth,
                                                                    dynamicVideoHeight,
                                                                    Double.parseDouble(longitude),
                                                                    Double.parseDouble(latitude)
                                                            );
                                                        }else{
                                                            showToast(domain.getMessage());
                                                        }

                                                        break;
                                                    default:
                                                        showToast(domain.getMessage());
                                                        break;
                                                }
                                            }
                                        }
                                    });


                        }else{
                            showToast(domain.getMessage());
                        }


                        break;
                    default:
                        showToast(domain.getMessage());
                        break;
                }


        }

        @Override
        public void onRemove(Progress progress) {

        }
    }




}
